package main.classical;

/**
 * @Description: TODO 经典查询题目收集
 * @Author: Take-off
 * @Date: 2023/8/14 7:28 PM
 * @Param
 * @return
 * @Version: 1.0
 **/
public class SortMethod {

    //二分查找
    //temp : 在排序数组中查找元素的第一个和最后一个位置
    public int[] searchRange(int[] nums, int target) {
        int start = middle(nums, target); // 选择其中一种写法即可
        if (start == nums.length || nums[start] != target)
            return new int[]{-1, -1};
        // 如果 start 存在，那么 end 必定存在
        int end = middle(nums, target + 1) - 1;
        end = Math.max(end, 0);
        return new int[]{start, end};
    }
    //找到数 <= target
    public  int middle(int[] nums, int target){
        int left = 0;
        int right = nums.length -1;
        while (left <= right){
            int mid = (left+ right) /2;
            if (nums[mid] < target){
                left = mid + 1;
            }else {
                right = mid - 1;
            }
        }
        return left;
    }

    public int searchMint(int[] nums, int target){
        int left = 0;
        int right = nums.length -1;
        while (left <= right){
            int mid = left + (right - left) / 2;
            if (nums[mid] > target){
                right = mid-1;
            }else if (nums[mid] < target){
                left = mid+1;
            }else {
                return mid;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] temp = {2,3,5,6,7,8};
        SortMethod sortMethod = new SortMethod();
        int i = sortMethod.searchMint(temp, 4);
        System.out.println(i);

    }


}
